package top.eggcode.arm.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.eggcode.arm.model.App;
import top.eggcode.arm.store.AppStore;
import top.eggcode.plugins.notice.dingtalk.DingMessage;
import top.eggcode.plugins.notice.dingtalk.DingRobotClient;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
@Service
public class AppAlertService {

    private final AppStore appStore;

    private final DingRobotClient robotClient;

    /**
     * 发送离线通知
     *
     * @param appId
     */
    public void sendOfflineNotice(String appId) {
        App app = appStore.findById(appId).get();
        // 10 分钟内通知一次
        if (app.getLastNoticeTime().plusMinutes(10).compareTo(LocalDateTime.now()) < 0) {
            String markdown = "## ".concat("ARM 应用监测").concat("\n")
                    .concat("#### 时间：").concat(
                            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                    ).concat("\n")
                    .concat("#### 名称：").concat(app.getName()).concat("\n")
                    .concat("#### 状态：").concat("状态离线，请尽快处理！");

            DingMessage dingMessage = DingMessage.builder()
                    .setMarkdownContent("检测到[".concat(app.getName()).concat("]离线！"), markdown)
                    .atMobile(app.getNoticeAddress())
                    .toMessage();

            try {
                robotClient.pushMessage(dingMessage);
            } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException ex) {
                ex.printStackTrace();
                log.error("钉钉通知失败");
            }
            log.info("发送钉钉通知，成功");

            app.setLastNoticeTime(LocalDateTime.now());
            appStore.save(app);
        }


    }

    /**
     * 发送上线通知
     *
     * @param appId
     */
    public void sendRecoveryNotice(String appId) {
        App app = appStore.findById(appId).get();
        String markdown = "## ".concat("ARM 应用监测").concat("\n")
                .concat("#### 时间：").concat(
                        LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                ).concat("\n")
                .concat("#### 名称：").concat(app.getName()).concat("\n")
                .concat("#### 状态：").concat("状态正常，已恢复上线！");

        DingMessage dingMessage = DingMessage.builder()
                .setMarkdownContent("[".concat(app.getName()).concat("] 已恢复上线！"), markdown)
                .atMobile(app.getNoticeAddress())
                .toMessage();

        try {
            robotClient.pushMessage(dingMessage);
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException ex) {
            ex.printStackTrace();
            log.error("钉钉通知失败");
        }
        log.info("发送钉钉通知，成功");
        appStore.save(app);
    }
}
